package com.yl.order.interfaces;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;

import com.yl.order.ui.adapter.BaseMoveAdapter;

import java.util.Collections;

/**
 * create by cjx on 2024/12/16
 * desc: 
 */
public class ItemTouchCallback extends ItemTouchHelper.Callback {

    BaseMoveAdapter<?> adapter;

    OnMoveCallback callback;

    public ItemTouchCallback(BaseMoveAdapter<?> adapter, OnMoveCallback callback) {
        this.adapter = adapter;
        this.callback = callback;
    }

    @Override
    public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
        int swipeFlags = 0; // 不支持滑动
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder source, @NonNull RecyclerView.ViewHolder target) {
        int fromPosition = source.getAdapterPosition();
        int toPosition = target.getAdapterPosition();
        // 更新位置
        Collections.swap(adapter.getList(), fromPosition, toPosition);
        adapter.notifyItemMoved(fromPosition, toPosition);
        if(callback != null) {
            callback.move(fromPosition, toPosition);
        }
        return true;
    }

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {

    }

    public interface OnMoveCallback {
        void move(int from, int to);
    }
}
